//
//  KYZXVideoHeadlineVC.m
//  KuYouZiXun
//
//  Created by lanou on 15/8/10.
//  Copyright (c) 2015年 lanou. All rights reserved.
//

#define kURL @"http://appapi.gamersky.com/v1/videotop"

#define kSlideUrl @"http://appapi.gamersky.com/v1/vslide"

#import "KYZXVideoHeadlineVC.h"

#import "KYZXVideoCollectionViewCell.h"

#import "KYZXVideoListModel.h"

#import "LJRequestManagerBlock.h"

#import "KYZXScreen.h"

#import "LJScrollView.h"

#import "UIImageView+WebCache.h"

#import "KYZXUserInfo.h"

#import "MJRefresh.h"
typedef NS_ENUM(NSInteger, RefreshType) {
    RefreshNew,
    RefreshMore,
    RefreshError//没有网的时候
};
@interface KYZXVideoHeadlineVC ()<LJScrollViewDelegate>
{
    RefreshType _refreshType;
}
@property (strong, nonatomic)NSMutableArray *dataSource;

@property (strong, nonatomic)NSMutableArray *slideDataSource;

@property (strong, nonatomic)NSMutableDictionary *parameterDic;//参数字典

@end

@implementation KYZXVideoHeadlineVC

static NSString * const reuseIdentifier = @"Cell";



- (void)addRefreshNew
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.header = [MJRefreshNormalHeader headerWithRefreshingBlock:^{
        _refreshType = RefreshNew;
        [self.parameterDic setValue:@"1" forKey:@"pageIndex"];
        [self requestData:self.parameterDic];
    }];
    // 马上进入刷新状态
    [self.collectionView.header beginRefreshing];
}

- (void)addRefreshMore
{
    // 设置回调（一旦进入刷新状态就会调用这个refreshingBlock）
    self.collectionView.footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        _refreshType = RefreshMore;
        NSString *page = [self.parameterDic valueForKey:@"pageIndex"];
        NSInteger pageNew = [page integerValue] + 1;
        
        [self.parameterDic setValue:[NSString stringWithFormat:@"%d",pageNew] forKey:@"pageIndex"];
        NSMutableDictionary *dic = [NSMutableDictionary dictionaryWithDictionary:self.parameterDic];
        [self requestData:dic];
    }];
}

- (void)endRefreshing{
    
    if (_refreshType == RefreshNew) {
        [self.collectionView.header endRefreshing];
        [self addRefreshMore];
    }
    if (_refreshType == RefreshMore) {
        [self.collectionView.footer endRefreshing];
    }
    
}

- (void)dealloc{

    [[KYZXUserInfo standardKYZXUserInfo] removeObserver:self];
}

- (NSMutableArray *)dataSource{

    if (_dataSource == nil) {
        _dataSource =[[NSMutableArray alloc] initWithCapacity:0];
    }
    return _dataSource;
}


- (NSDictionary *)parameterDic{

    if(_parameterDic == nil){
        _parameterDic = [@{@"pageIndex":@"1",@"pageCount":@"20"} mutableCopy];
    }
    return _parameterDic;
}

- (NSMutableArray *)slideDataSource{

    if (_slideDataSource == nil) {
        _slideDataSource = [[NSMutableArray alloc] initWithCapacity:0];
    }
    return _slideDataSource;
}

#pragma mark 获取数据


//头条轮播图获取数据
- (void)requestSlideData{

    [LJRequestManagerBlock manager:POST requestWith:kSlideUrl dic:@{@"parentId" : @"-1"} finish:^(NSData *data) {
        NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
        NSArray *resultArray = dataDict[@"result"];
        for (NSDictionary *dic in resultArray) {
            KYZXVideoListModel *model = [[KYZXVideoListModel alloc] init];
            [model setValuesForKeysWithDictionary:dic];
            [self.slideDataSource addObject:model];
        }
        [self.collectionView reloadData];
    } error:^(NSError *error) {
    }];
}


- (void)requestData:(NSDictionary *)dic{

    [LJRequestManagerBlock manager:POST requestWith:kURL dic:dic finish:^(NSData *data) {
        [self parseData:data];
    } error:^(NSError *error) {
        
    }];
}


- (void)parseData:(NSData *)data
{
    //程序第一次尽量的时候没有网,数据库里面也没有数据 所以会蹦,我们判断一下如果data为nil 直接返回
    if (data == nil) {
        //        NSLog(@"即没有网 数据库也没有数据");
        [self endRefreshing];
        return;
    }
    if (_refreshType == RefreshNew) {
        self.dataSource = nil;
    }
    NSDictionary *dataDict = [NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableContainers|NSJSONReadingMutableLeaves error:nil];
    NSArray *resultArray = dataDict[@"result"];
    for (NSDictionary *dic in resultArray) {
        KYZXVideoListModel *model = [[KYZXVideoListModel alloc] init];
        [model setValuesForKeysWithDictionary:dic];
        [self.dataSource addObject:model];
    }
    [self endRefreshing];
    [self.collectionView reloadData];
}


- (void)viewDidLoad {
    [super viewDidLoad];
    [self requestSlideData];
    [self addRefreshNew];
    [self.collectionView registerNib:[UINib nibWithNibName:@"KYZXVideoCollectionViewCell" bundle:nil] forCellWithReuseIdentifier:reuseIdentifier];
   [self.collectionView registerClass:[UICollectionReusableView class] forSupplementaryViewOfKind:UICollectionElementKindSectionHeader withReuseIdentifier:@"header"];
    self.collectionView.backgroundColor = [[KYZXUserInfo standardKYZXUserInfo] backgroundColor];
    [[KYZXUserInfo standardKYZXUserInfo] addObserver:self];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
   
}


#pragma mark <UICollectionViewDataSource>

- (NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView {
    
    return 1;
}


- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {

    return [_dataSource count];
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    
    KYZXVideoListModel *model = _dataSource[indexPath.item];
    KYZXVideoCollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:reuseIdentifier forIndexPath:indexPath];
    
    cell.model = model;
    return cell;
}



//自定义头视图
- (UICollectionReusableView *)collectionView:(UICollectionView *)collectionView viewForSupplementaryElementOfKind:(NSString *)kind atIndexPath:(NSIndexPath *)indexPath
{
    
    UICollectionReusableView *view = [collectionView dequeueReusableSupplementaryViewOfKind:kind withReuseIdentifier:@"header"forIndexPath:indexPath];
    if (kind == UICollectionElementKindSectionHeader)
    {
        if ([self.slideDataSource count] != 0) {
            NSMutableArray *viewArray = [[NSMutableArray alloc] initWithCapacity:0];
            for (int i = 0 ; i < [self.slideDataSource count]; i++) {
                KYZXVideoListModel *model = _slideDataSource[i];
                UIImageView *imageView = [[UIImageView alloc] initWithFrame:view.bounds];
                [imageView sd_setImageWithURL:[NSURL URLWithString:model.thumbnailUrl] placeholderImage:[UIImage imageNamed:@"_backimage"]];
                [viewArray addObject:imageView];
            }
            LJScrollView *scrollView = [[LJScrollView alloc] initWithFrame:view.bounds viewArray:viewArray Animation:5];
            [view addSubview:scrollView];
            scrollView.delegate = self;

        }
    }
        return view;
}


//点击轮播图执行
//代理方法 点击scrollView的时候将当前的一些值传出去
- (void)scrollViewDidEndSelected:(LJScrollView *)scrollView viewArray:(NSArray *)viewArray atIndex:(NSUInteger)index{

    KYZXVideoListModel *model = _slideDataSource[index];
    
}

- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForHeaderInSection:(NSInteger)section
{
    //返回头视图size
    return CGSizeMake(SCREEN_WIDTH, 180 / 320.0 * SCREEN_WIDTH);
}


//点击跳转
- (BOOL)collectionView:(UICollectionView *)collectionView shouldSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
    KYZXVideoListModel *model = _dataSource[indexPath.item];
    return YES;
}


- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context{

    self.collectionView.backgroundColor = [KYZXUserInfo standardKYZXUserInfo].backgroundColor;
}



@end
